﻿namespace Encloser
{
    public static class StringUtils
    {
        public static string Trim(this string text, params char[] chars)
        {
            if (ValidUtils.IsEmpty(text, chars)) return text;
            var k = text.ToCharArray();
            var i = -1;
            var j = k.Length;
            while (++i < j && k[i].SpaceIn(chars)) ;
            if (i == j) return string.Empty;
            while (--j >= i && k[j].SpaceIn(chars)) ;
            return i > j ? string.Empty : text.Substring(i, j - i + 1);
        }

        public static string TrimBegin(this string text, params char[] chars)
        {
            if (ValidUtils.IsEmpty(text, chars)) return text;
            var k = text.ToCharArray();
            var i = -1;
            while (++i < k.Length && k[i].SpaceIn(chars)) ;
            return i == k.Length ? string.Empty : text.Substring(i);
        }

        public static string TrimEnd(this string text, params char[] chars)
        {
            if (ValidUtils.IsEmpty(text, chars)) return text;
            var k = text.ToCharArray();
            var j = k.Length;
            while (--j >= 0 && k[j].SpaceIn(chars)) ;
            return j < 0 ? string.Empty : text.Substring(0, j + 1);
        }

        private static bool SpaceIn(this char ch, params char[] chars)
        {
            if (ch == ' ') return true;
            return ch.In(chars);
        }

        public static bool In(this char ch, params char[] chars)
        {
            foreach (char c in chars)
            {
                if (c == ch) return true;
            }
            return false;
        }

        public static int Where(this char ch, params char[] chars)
        {
            var i = 0;
            foreach (char c in chars)
            {
                if (c == ch) return i;
                i++;
            }
            return -1;
        }
    }
}
